import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import api from '../../api/axios'
import { Button, List, message, Modal, Space } from 'antd'
import logo from '../../image/logo.webp'
//input输入框适应文本域高度
import { Input } from 'antd';
const { TextArea } = Input;

function Index() {
  const { id } = useParams()
  const [list, setList] = useState([])
  const [value, setValue] = useState('')
  const [value1, setValue1] = useState('')
  const navigate = useNavigate()
  const getData = async () => {
    const res = await api.get(`/article/${id}`)
    console.log(res)
    setList(res.data)
  }
  const handsend = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      message.error('无登录,请先登录')
      navigate('/login')
    }
    if (value.length > 100) {
      message.error('内容不许超出100字')
      return;
    }
    if (!value.trim()) {
      message.error('内容不能为空')
      return;
    }
    const sendisit = value.replace(/傻逼|蠢货|你妈|操/g, '***')
    const res = await api.post('/discuss', {
      userId: 47529555,// 47529555 用户id
      content: sendisit,//评论内容
      //  commentId:number,//评论ID（非必填，回复评论时使用）
      articleId: Number(id) // 文章id 90
    })
    console.log(res)
    getData()
    setValue('')
    message.success('评论成功')
  }
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const handleOk = async () => {
    const res = await api.post('/discuss', {
      userId: 47529555,// 47529555 用户id
      content: value1,//评论内容
      //  commentId:number,//评论ID（非必填，回复评论时使用）
      articleId: Number(id), // 文章id 90
      commentId: open.commentId
    })
    console.log(res)
    setValue1('')
    getData()
    message.success('回复成功')
    setOpen(false)
  }
  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };
  useEffect(() => {
    getData()
  }, [])
  return (
    <div>
      <div>
        <div style={{ lineHeight: '60px' }}>
          <h2>标题:{list.title}</h2>
          <span>时间:{list.createdAt}</span>
          <p>浏览量:{list.viewCount}</p>
          <b>内容:{list.content}</b>
        </div>
        <TextArea
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder="Controlled autosize"
          autoSize={{ minRows: 3, maxRows: 5 }}
        />
        <Button style={{ marginTop: '20px' }} onClick={() => handsend()} >发送评论</Button>
        <hr style={{ marginTop: "8px" }} />
      </div>
      {/* 渲染评论内容 */}
      <div>
        <List
          style={{ overflow: 'auto', height: '430px' }}
          dataSource={list.comments}
          renderItem={(item) => (
            <div style={{ marginTop: '25px' }}>
              <Space align='start'>
                <img style={{ width: '35px', height: '35px', borderRadius: '50%' }} src={`https://picsum.photos/150/150?random=${item.id}`} alt="" />
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <p>{item.user.username}</p>
                  <p style={{ marginLeft: '10px' }}>{item.user.createdAt}</p>
                  <br />
                </div>
              </Space>
              <br /><b style={{ marginLeft: '50px' }}>{item.content}</b>
              <Button style={{ marginLeft: '18px' }} onClick={() => setOpen({ username: item.user.username, commentId: item.id })}>回复评论</Button>
              {/* 回复评论渲染 */}
              <div>
                {
                  item.replies && item.replies.length > 0 && (
                    <List
                      style={{ overflow: 'auto'}}
                      dataSource={item.replies}
                      renderItem={(it) => (
                        <div style={{ marginTop: '10px',marginLeft:'20px' }}>
                          <Space align='start'>
                            <img style={{ width: '35px', height: '35px', borderRadius: '50%' }}  src={`https://picsum.photos/150/150?random=${it.id}`} alt="" />
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                              <p>{it.user.username}</p>
                              <p style={{ marginLeft: '10px' }}>{it.user.createdAt}</p>
                              <br />
                            </div>
                          </Space>
                          <br /><b style={{ marginLeft: '50px' }}>{it.content}</b>
                        </div>
                      )}
                    />
                  )
                }
              </div>
            </div>
          )}
        />
        <Modal
          title="回复评论"
          open={open}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <TextArea
            value={value1}
            onChange={(e) => setValue1(e.target.value)}
            placeholder="Controlled autosize"
            autoSize={{ minRows: 3, maxRows: 5 }}
          />
        </Modal>
      </div>
    </div>
  )
}

export default Index
